package cn.flying.cloud.flow.core.listener.event.callback;


import javax.annotation.Resource;

import java.time.ZoneId;

import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.flowable.engine.runtime.ProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cn.flying.cloud.flow.bo.FwProcInstBo;
import cn.flying.cloud.flow.service.FwProcInstService;

/**
 * 流程创建监听
 *
 * @author: admin
 * @date: 2023年02月26日 08:20
 * @version: 1.0
 */
@Component
public class ProcessCreatedListenerCallback implements EventListenerCallback {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private FwProcInstService procInstService;

    @Override
    public void execute(FlowableEvent event) {
        logger.info("==========流程创建监听器回调处理---start===========");
        logger.info("监听事件类型：{}", event.getType().name());
        FlowableEntityEventImpl entityEvent = (FlowableEntityEventImpl) event;
        ExecutionEntityImpl entity = (ExecutionEntityImpl) entityEvent.getEntity();

        FwProcInstBo inst = new FwProcInstBo();
        inst.setProcInstId(((ProcessInstance) entity).getProcessInstanceId());
        inst.setProcInstName(((ProcessInstance) entity).getName());
        inst.setBizKey(((ProcessInstance) entity).getBusinessKey());
        inst.setStartTime(((ProcessInstance) entity).getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
//        inst.setEndTime(LocalDateTime.now());
//        inst.setDuration();
        inst.setStartUser(((ProcessInstance) entity).getStartUserId());
        inst.setProcStatus(((ProcessInstance) entity).getBusinessStatus());
//        inst.setNodeId("");
//        inst.setNodeName("");
//        inst.setTaskId("");
//        inst.setAssignee("");
        inst.setProcDefId(((ProcessInstance) entity).getProcessDefinitionId());
        inst.setProcDefKey(((ProcessInstance) entity).getProcessDefinitionKey());
        inst.setProcName(((ProcessInstance) entity).getProcessDefinitionName());
//        inst.setRemark("");

        procInstService.createObj(inst);
        logger.info("实例【{}】创建成功，实例ID：【{}】，业务流水号：【{}】", entity.getProcessDefinitionId(), entity.getProcessInstanceId(), entity.getBusinessKey());
        logger.info("==========流程创建监听器回调处理---end===========");
    }
}
